/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlet;

import ejb.sessionBeans.AvisoFacadeRemote;
import ejb.sessionBeans.EstadoFacadeRemote;
import ejb.sessionBeans.TipoavisoFacadeRemote;
import ejb.sessionBeans.UsuarioFacadeRemote;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.jms.*;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import modelo.Aviso;
import modelo.Estado;
import modelo.Tipoaviso;
import modelo.Usuario;

/**
 *
 * @author inftel
 */
@WebServlet(name = "ReceptorPaSOS", urlPatterns = {"/ReceptorPaSOS"})
public class ReceptorPaSOS extends HttpServlet {

    @Resource(mappedName = "jms/Avisos")
    private Queue avisos;
    @Resource(mappedName = "jms/AvisosFactory")
    private ConnectionFactory avisosFactory;
    @EJB
    private EstadoFacadeRemote estadoFacade;
    @EJB
    private TipoavisoFacadeRemote tipoavisoFacade;
    @EJB
    private AvisoFacadeRemote avisoFacade;
    @EJB
    private UsuarioFacadeRemote usuarioFacade;

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, ParseException, JMSException {
        System.out.println("Entrando en el servidor ReceptorPaSOS");
        
        // Send to client
        ServletOutputStream out = response.getOutputStream();
        DataOutputStream dos = new DataOutputStream(out);
        
        // Receive from client
        ServletInputStream in = request.getInputStream();
        DataInputStream dis = new DataInputStream(in);
        
        String xid, rd, dt, la, pb, lt, ln, lh, ld;
        ld = "20000606";
        lh = "200000";
        ln = "0";
        lt = "0";
        xid="";
        rd="";
        dt="";
        la="";
        pb="";
//        String trama = request.getParameter("trama");
        String trama = dis.readUTF();

        //String trama="$AU1&LD20120304&LH060654&LN1008052067&LT153052067&XID666111111#";

        //Rellenamos el obejto aviso
        Aviso aviso = new Aviso();
        String ini = trama.substring(0, 2);
        System.out.println("Inicio " + ini);
        String fin = trama.substring(trama.length() - 1, trama.length());
        System.out.println("Fin " + fin);
        if ("*$".equals(ini) && "#".equals(fin)) {

            trama = trama.substring(2, trama.length() - 1);
            System.out.println("trama sin *$# " + trama);
            Tipoaviso au;
            Usuario usuario;
            String[] etiquetas = trama.split("&");
            int i;
            for (i = 0; i < etiquetas.length; i++) {
                String aux = etiquetas[i];
                Pattern patron = Pattern.compile("([A-Z]+)"); //Cojo el primer grupo de caracteres
                Matcher matcher = patron.matcher(aux);
                matcher.find();
                Pattern patron2 = Pattern.compile("([0-9]+)"); //Cojo el grupo de digitos
                Matcher matcher2 = patron2.matcher(aux);
                matcher2.find();
                Pattern patron3 = Pattern.compile("((\\-?)[0-9]+\\.[0-9]+)"); //Cojo el grupo de digitos
                Matcher matcher3 = patron3.matcher(aux);
                matcher3.find();

                System.out.println(aux);
                if ("AU".equals(matcher.group(1))) {
                    System.out.println((matcher2.group(1)));

                    au = tipoavisoFacade.find(Integer.parseInt(matcher2.group(1)));
                    aviso.setIdTipoaviso(au);


                } else if ("AD".equals(matcher.group(1))) {
                    System.out.println((matcher2.group(1)));
                    au = tipoavisoFacade.find(Integer.parseInt(matcher2.group(1)));

                    aviso.setIdTipoaviso(au);

                } else if ("LD".equals(matcher.group(1))) {
                    System.out.println((matcher2.group(1)));
                    ld = matcher2.group(1);

                } else if ("LH".equals(matcher.group(1))) {
                    System.out.println((matcher2.group(1)));
                    lh = matcher2.group(1);

                } else if ("LN".equals(matcher.group(1))) {
                    System.out.println((matcher2.group(1)));
                    ln = dmsToDd(matcher2.group(1));

                } else if ("LT".equals(matcher.group(1))) {
                    System.out.println((matcher2.group(1)));
                    lt = dmsToDd(matcher2.group(1));

                } else if ("PB".equals(matcher.group(1))) {
                    System.out.println((matcher2.group(1)));
                    pb = matcher2.group(1);

                } else if ("LA".equals(matcher.group(1))) {
                    System.out.println((matcher2.group(1)));
                    la = dmsToDd(matcher2.group(1));

                } else if ("DT".equals(matcher.group(1))) {
                    System.out.println((matcher2.group(1)));
                    dt = matcher2.group(1);

                }  else if ("XID".equals(matcher.group(1))) {
                    System.out.println((matcher2.group(1)));
                    xid = matcher2.group(1);
                    usuario = usuarioFacade.findByPhone(xid);
                    aviso.setIdUsuario(usuario);

                }

            }
            ld=ld.substring(6, 8)+"/"+ld.substring(4, 6)+"/"+ld.substring(0,4);
            lh=lh.substring(0, 2)+":"+lh.substring(2, 4)+":"+lh.substring(4, 6);
            String fechaString = ld + " " + lh;
            Date date;
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
            System.out.println("Formato fecha: "+fechaString);
            date = (Date) sdf.parse(fechaString);
            System.out.println("Fecha tipo date: "+date);

            String des="";
            if(!"".equals(pb)){
                des=des+"Bateria: "+pb;
            }
            if(!"".equals(dt)){
                des=des+" Temperatura: "+dt;
            }
           
            Estado estado = estadoFacade.findByDescripcion("Pendiente");

            // aviso.setIdAviso(1);
            aviso.setDescripcion(des);
            aviso.setLatitud(lt);
            aviso.setLongitud(ln);
            aviso.setHoraAviso(date);
            aviso.setIdEstado(estado);
            //Se supone que esto guarda en la BD  
            sendJMSMessageToAvisos(aviso);

            dos.writeUTF("OK: Aviso recibido correctamente");

        } else {
           dos.writeUTF("ERROR: Aviso mal recibido");
        }
        dis.close();
        dos.close();
    }
    
    private String dmsToDd (String dms){
    
        String dd="";
            if("2".equals(dms.substring(0, 1))){
                dd="-";
            }
            
            
            Float grados=Float.parseFloat(dms.substring(1, 3));
            
            Float minutos=Float.parseFloat(dms.substring(3, 5));
            minutos=minutos/60;
            
            Float segundos=Float.parseFloat(dms.substring(5, 9));
            segundos=segundos/100;
            segundos=segundos/3600;
            
            grados=grados+minutos+segundos;
            
            dd=dd+grados.toString();
        
       return dd;
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (ParseException ex) {
            Logger.getLogger(ReceptorPaSOS.class.getName()).log(Level.SEVERE, null, ex);
        } catch (JMSException ex) {
            Logger.getLogger(ReceptorPaSOS.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (ParseException ex) {
            Logger.getLogger(ReceptorPaSOS.class.getName()).log(Level.SEVERE, null, ex);
        } catch (JMSException ex) {
            Logger.getLogger(ReceptorPaSOS.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private Message createJMSMessageForjmsAvisos(Session session, Object messageData) throws JMSException {
        // TODO create and populate message to send
        Message msg;
        if (messageData instanceof String) {
            TextMessage tm = session.createTextMessage();
            tm.setText(messageData.toString());
            msg = tm;
        } else {
            ObjectMessage om = session.createObjectMessage();
            om.setObject((Serializable) messageData);
            msg = om;
        }
        return msg;
    }

    private void sendJMSMessageToAvisos(Object messageData) throws JMSException {
        Connection connection = null;
        Session session = null;

        try {

            connection = avisosFactory.createConnection();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            MessageProducer messageProducer = session.createProducer(avisos);
            messageProducer.send(createJMSMessageForjmsAvisos(session, messageData));
        } finally {
            if (session != null) {
                try {
                    session.close();
                } catch (JMSException e) {
                    Logger.getLogger(this.getClass().getName()).log(Level.WARNING, "Cannot close session", e);
                }
            }
            if (connection != null) {
                connection.close();
            }
        }

    }
}
